<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页版涂鸦</title>
</head>

<body>
    <div style="text-align: center;">
        <canvas id="canElem">

        </canvas>
        <footer>by ma rong yi <br>2023.11.10</footer>
    </div>
    <!-- 在js中绘制图形 -->
    <script>
        //获得画布
        var canvas = document.getElementById('canElem');
        //准备画笔（获得画布的上下文）
        var context = canvas.getContext('2d');
        //设置画笔属性
        context.linewidth = '3';
        context.strokeStyle = '#f00';
        context.lineCap = 'round';
        //设置画布的属性
        canvas.width = 900;
        canvas.height = 600;
        canvas.style.border = '1px solid #aaa';

        //鼠标按下触发事件onmousedown，事件绑定函数
        canvas.onmousedown = function(e) {
            // console.log(canvas.getBoundingClientRect());
            // console.log(e.clientX, e.clientY);
            var x = e.clientX - canvas.getBoundingClientRect().left; //画布中坐标x
            var y = e.clientY - canvas.getBoundingClientRect().top; //画布中坐标
            context.beginPath(); //开始规划路径
            context.moveTo(x, y); //定义画布中的起点位置
            //鼠标移动，绘图
            canvas.onmousemove = function(event) {
                    // console.log('绘图中......');

                    var x = event.clientX - canvas.getBoundingClientRect().left; //画布中坐标x
                    var y = event.clientY - canvas.getBoundingClientRect().top; //画布中坐标y
                    context.lineTo(x, y) //设置端点
                    console.log(x);
                    context.stroke(); //描边
                }
                //鼠标松开停止绘图
            canvas.onmouseup = function() {
                console.log('cancle')
                canvas.onmousemove = null
            }
        }
    </script>
</body>

</html>